package com.zoffy.ybuhelper.fragment;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.zoffy.ybuhelper.MyApplication;
import com.zoffy.ybuhelper.adapter.CategoryRecyclerAdapter;
import com.zoffy.ybuhelper.adapter.EatRecyclerAdapter;
import com.zoffy.ybuhelper.dao.CategoryDao;
import com.zoffy.ybuhelper.database.YBUDatabase;
import com.zoffy.ybuhelper.pojo.entity.Category;

import java.util.List;

public class CategoryControlFragment extends ItemControlFragment{
    private List<Category> dataList;
    private CategoryDao categoryDao;
    private CategoryRecyclerAdapter adapter;

    public CategoryControlFragment(String type, String topBarText) {
        super(type, topBarText);
    }

    @Override
    protected void dataInit() {
        YBUDatabase YBUDatabase = MyApplication.getInstance().getYBUDatabase();
        categoryDao = YBUDatabase.categoryDao();
        dataList=categoryDao.getAll();


    }

    @Override
    protected void showDelete() {
        adapter.changeCouldDelete();
    }

    @Override
    protected void adapterInit() {
        adapter=new CategoryRecyclerAdapter(dataList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false);
        adapter.setSetItemOnclick(new EatRecyclerAdapter.SetItemOnclick() {
            @Override
            public void onDeleteClick(int position) {
                Category category=(Category) adapter.getDataListAt(position);
                int id=category.getId();
                categoryDao.deleteById(id);
                adapter.deleteItem(position);
                adapter.notifyItemRemoved(position);
            }

            @Override
            public void onChangeClick(int position) {
                AddItemFragment childFragment=new AddItemFragment();
                Category category=(Category) adapter.getItemAt(position);
                Bundle bundle=new Bundle();
                bundle.putString("type","change_category");
                bundle.putInt("id",category.getId());
                childFragment.setArguments(bundle);
                childFragment.show(fragmentManager,"add_item_dialog");
            }
        });
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void update() {
        dataList=categoryDao.getAll();
        adapterInit();
    }
}
